<template>
  <div>
    <div>
      <!-- 面包屑导航区域 -->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>编辑内容</el-breadcrumb-item>
        <el-breadcrumb-item>分类列表</el-breadcrumb-item>
        <el-breadcrumb-item>
          <span v-if="this.flag === '1'">添加分类</span>
          <span v-else-if="this.flag === '0'">编辑分类</span>
        </el-breadcrumb-item>
        <p><br></p>
      </el-breadcrumb>
    </div>

    <div style="text-align: left">

      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="120px" title="保存分类信息">

        <el-form-item label="分类名" prop="catname">
          <el-input v-model="ruleForm.catname" style="width: 593px"></el-input>
        </el-form-item>

        <el-form-item style="width: 600px; text-align: center">
          <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  name: "SaveCategory",
  data() {
    return {
      flag: 1,
      ruleForm: {
        id: 0,
        catname: ''
      },
      rules: {
        catname: [
          {required: true, message: '请输入分类名', trigger: 'blur'},
          {min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur'}
        ]
      }
    }
  },
  mounted() {
    this.flag = this.$route.query.flag;
    if (this.flag === '0') {
      this.$http.get("/api/category/" + this.$route.query.categoryId)
          .then(res => {
            this.ruleForm = res.data;
          })
          .catch(res => {
            this.$message.error("获取分类信息失败")
          })
    }
  },
  methods: {
    cancel() {
      this.$router.push("/categoryList");
    },
    saveCategory() {
      this.$http.post("/api/category/save", this.ruleForm)
          .then(res => {
          })
          .catch(res => {
            this.$message.error("保存失败")
            return false;
          })
      return true;
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (!this.saveCategory()) {
            return;
          }
          this.$message.success("保存成功")
          // 更新成功后,跳转到演员列表页面
          this.$router.push("/categoryList")
        } else {
          this.$message.error("保存失败,请注意格式")
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
}
</script>

<style scoped>
#el-input {
  width: 400px;
}

.template_title {
  line-height: 40px;
  width: 500px;
  text-align: center;
  height: 60px;
  margin-top: 0px;
  font-size: 24px;
  color: #226655;
}
</style>